<?php
class Dbt {
	private $db;
	private $table;
	private $pairs;
	private $prefix;
	private $tablefileds;
    
    public $_debug = false;

function __construct($db,$table,$pairs){
	global ${$db};
	$this->db = ${$db};
	$this->prefix =$this->db->getc('prefix');
	$this->table =$this->prefix."_".$table;
	$this->pairs =$pairs;
	$this->tablefileds =$this->getFieldByTable();
	}

function __destruct(){
	@mysql_free_result();
	}
/**
 *设置_debug
 * @param type $_debug 
 */
function debug($debug){
    $this -> _debug = $debug;
}
function getInsertSQL ($type=0) {
		$pairs = $this->getDealPairs();
		$sql = " insert into `".$this->table."` ";
		$sql.= " ( `" . join(array_keys($pairs),"`,`") . "`) ";
		$sql.= " values ";
		$sql.= " ('". join(array_values($pairs),"','")."')";
        if($this -> _debug){
            die($sql);
        }
		$query=$this->db->Desql($sql);
		if($type){
		return $sql;
		}else{
		return $query;
		}
	}
function getUpdateSQL( $key,$val,$type=0 ){
		$pairs = $this->getDealPairs();
		$sql = " update `" .$this->table. "` ";
		array_walk($pairs, create_function('&$value,$name', '$value = $name . "` = \'$value\'";'));
		$sql .= " set `" . join(array_values($pairs),",`");
		$sql .= " where ".$key." = '".$val."'";
        if($this -> _debug){
            die($sql);
        }
		$query=$this->db->Desql($sql);
		if($type){
		return $sql;
		}else{
		return $query;
		}
	}
function getDeleteSQL($key,$val,$type=0,$num=1){
		//$pairs = $this->getDealPairs();
		$sql = " DELETE FROM `" .$this->table. "` ";
		//array_walk($pairs, create_function('&$value,$name', '$value = $name . "` = \'$value\'";'));
		//$sql .= "WHERE `" . join(array_values($pairs),"or`");
		$sql .= " where ".$key." = '".$val."'";
		if($num!=0){
			$sql .= " limit ".$num." ;";
		}
        if($this -> _debug){
            die($sql);
        }
		$query=$this->db->Desql($sql);
		if($type){
		return $sql;
		}else{
		return $query;
		}
	}
function getFieldByTable () {
		$query=$this->db->Desql("select * from `".$this->table."` where 1 limit 1");
		while($obj = mysql_fetch_field($query) ){
			$result[] = $obj->name;
		}
		return $result;
	}


function getNewPairsKeys () {
		$temp=array_keys($this->pairs);
		foreach( $temp as $primalPairsKeys ){
			if ( in_array( $primalPairsKeys , $this->tablefileds) ) {
				$result[$primalPairsKeys] = $primalPairsKeys;
			}
		}
		unset($result[0]);
		return $result;
	}
function getDealPairs () {
		$temp=$this->getNewPairsKeys();
		foreach( $temp as $key=>$val ){
			$result[$key] = $this->pairs[$val];
		}
		return $this->daddslashes($result);
	}
function daddslashes($string, $force = 0) {
		if(!get_magic_quotes_gpc() || $force) {
			if(is_array($string)) {
				foreach($string as $key => $val) {
					$string[$key] = $this->daddslashes($val, $force);
				}
			} else {
				$string = addslashes($string);
			}
		}
		return $string;
	}

}
?>